<template>
  <el-select
    v-model="localValue"
    filterable
    remote
    reserve-keyword
    placeholder="工程师"
    :remote-method="searchEngineer"
    :loading="loading"
    clearable
    class="w-100px"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item"
    ></el-option>
  </el-select>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { engineerService } from '@/services/business/engineer.service';
import type { Engineer, EngineerOption } from '@/types/business/engineer';

const props = defineProps({
  modelValue: {
    required: true,
    type: null as unknown as undefined,
  },
});

const emit = defineEmits(['update:modelValue']);

const localValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

const options = ref<EngineerOption[]>([]);
const loading = ref(false);

const searchEngineer = async (query: string) => {
  if (query) {
    loading.value = true;
    try {
      const response = await engineerService.searchEngineers(query);
      options.value = response.records.map((e: Engineer) => ({
        value: e.id,
        label: e.name,
      }));
    } catch (error) {
      console.error('Error searching engineers:', error);
      options.value = [];
    } finally {
      loading.value = false;
    }
  } else {
    options.value = [];
  }
};
</script>
